import {  PlusOutlined } from '@ant-design/icons';
import {
  type ActionType,
  ModalForm,
  type ProColumns,
  ProFormDigit,
  ProFormGroup,
  ProTable
} from '@ant-design/pro-components';
import {Button, message, Tag} from 'antd';
import React, {useEffect, useRef, useState} from "react";
import {addStockInOrder, listStockInOrderVoByPage} from "@/services/stockIn/api";



import {
  ProForm,
  ProFormText,
  ProFormList,
} from '@ant-design/pro-components';


type StockInFormProps = {
  open: boolean;
  onCancel: () => void;
}

const StockInForm: React.FC<StockInFormProps> = (props) => {
  const handleCreate= async (valuse: StockInDTO)=>{
    const res = await addStockInOrder(valuse);
    if(res.code!=0 || res.data!=true){
      message.error("入库单创建失败"+res.message);
      return;
    }
    message.success("入库单创建成功");
    props.onCancel();
  }
  return (
    <ModalForm<StockInDTO>
      layout="vertical"
      open={props.open}
      onFinish={async (values) => {
        await handleCreate(values);
        // 这里处理提交逻辑
      }}
      submitter={{
        render: (_, dom) => <div style={{ textAlign: 'center' }}>{dom}</div>,
      }}
      modalProps={
        {
          destroyOnClose: true,
          onCancel: props.onCancel,
        }
      }
    >
      {/* 主单信息 */}
      <ProForm.Group>
        <ProFormText
          name="stockInNo"
          label="入库单号"
          width="md"
          rules={[{ required: true, message: '请输入入库单号' }]}
        />
        <ProFormText
          name="warehouseNo"
          label="仓库编号"
          width="md"
          rules={[{ required: true, message: '请输入仓库编号' }]}
        />
      </ProForm.Group>

      {/* 动态子单列表 */}
      <ProFormList
        name="stockInDetails"
        creatorButtonProps={{
          creatorButtonText: '添加入库明细',
          style: { width: '200px' },
        }}
        itemRender={({ listDom, action }, { index }) => (
          <div
            style={{
              position: 'relative',
              padding: 24,
              border: '1px solid #eee',
              marginBottom: 24,
            }}
          >
            {listDom}
            <div style={{ position: 'absolute', top: 8, right: 8 }}>
              {action}
            </div>
          </div>
        )}
      >
        <ProFormGroup>
          <ProFormText name='stockInDetailNo' label='入库子单号' required={true} />
          <ProFormText name='goodsNo' label='货品编码' required={true} />
          <ProFormText name='goodsName' label='货品名称'/>
          <ProFormDigit name='num' label='数量' required={true} initialValue={0}/>
        </ProFormGroup>
      </ProFormList>
    </ModalForm>
  );
};

const StockInAdd: React.FC = () => {
  const columns: ProColumns<API.StockInOrderVo>[] = [
    {
      title: '仓库名称',
      width: 120,
      dataIndex: 'warehouseName',
    },
    {
      title: '入库单号',
      width: 120,
      dataIndex: 'stockInNo',
    },
    {
      title: '状态',
      width: 120,
      hideInSearch: true,
      dataIndex: 'status',
      render: (text, record) => {
        if (record.status===90) {
          return <Tag color="#2db7f5">完成</Tag>;
        } else {
          return <Tag color="yellow">作业中</Tag>;
        }
      },
    },
    {
      title: '创建时间',
      width: 120,
      hideInSearch: true,
      dataIndex: 'createTime',
    }
  ];
  const actionRef = useRef<ActionType>();
  const [currentPage,setCurrentPage] = useState<number>(1);
  const [isCreate,setIsCreate] = useState<boolean>(false);
  const [data, setData] = useState<API.StockInOrderVo[]>([]);
  const [total,setTotal] = useState<number>(0);
  const loadData = async (params: any) => {
    const res = await listStockInOrderVoByPage({
      params : params,
      pageNum: currentPage,
      pageSize: 10,
    });
    if (res.code != 0) {
      message.error("入库单数据加载失败 " + res.message);
      return;
    }
    setData(res?.data?.records || []);
    setTotal(res?.data?.total || 0);
    console.log(data);
  }
  useEffect(() => {
    loadData({})
  }, [currentPage]);
  return (
    <>
        <ProTable<API.StockInOrderVo>
          columns={columns}
          actionRef={actionRef}
          cardBordered
          dataSource={data}
          request={async (params) => {
            await loadData(params);
            return data;
          }}
          editable={{
            type: 'multiple',
          }}
          rowKey="id"
          search={{
            labelWidth: 'auto',
          }}
          options={{
            setting: {
              listsHeight: 400,
            },
          }}
          pagination={{
            pageSize: 10,
            onChange: (page) => setCurrentPage(page),
            total: total,
          }}
          headerTitle="入库单"
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                // actionRef.current?.reload();
                setIsCreate(true);
              }}
              type="primary"
            >
              入库单创建
            </Button>,
          ]}
        />
        <StockInForm
          onCancel={()=>setIsCreate(false)}
          open={isCreate}
        />
    </>
  )
}
export default StockInAdd;


